<?php
namespace Think\Upload\Driver;
    /**
     *
     * @authors Your Name (you@example.org)
     * @date    2014-07-11 13:42:25
     * @version $Id$
     */

//require_once dirname(__FILE__) . '/Qcloud/cos-autoloader.php';
require(__DIR__ . DIRECTORY_SEPARATOR . '/Qcloud/cos-autoloader.php');

class Qcloud
{

    private $config = array(
        'AccessKeyId' => '', //OSS用户
        'AccessKeySecret' => '', //OSS密码
        'domain' => '',   //OSS空间路径
        'Bucket' => '', //空间名称
        'Endpoint' => '', //超时时间
    );

    /**
     * 本地上传错误信息
     * @var string
     */
    private $error = '';

    /**
     * 构造函数，用于设置上传根路径
     * @param array $config 配置
     */
    public function __construct($config)
    {
        /* 默认配置 */
        $this->config = array_merge($this->config, $config);
    }

    /**
     * 检测上传根目录(OSS上传时支持自动创建目录，直接返回)
     * @param string $rootpath 根目录
     * @return boolean true-检测通过，false-检测失败
     */
    public function checkRootPath($rootpath)
    {
        /* 设置根目录 */
        $this->rootPath = trim($rootpath, './') . '/';
        return true;
    }

    /**
     * 检测上传目录(OSS上传时支持自动创建目录，直接返回)
     * @param  string $savepath 上传目录
     * @return boolean          检测结果，true-通过，false-失败
     */
    public function checkSavePath($savepath)
    {
        return true;
    }

    /**
     * 创建文件夹 (OSS上传时支持自动创建目录，直接返回)
     * @param  string $savepath 目录名称
     * @return boolean          true-创建成功，false-创建失败
     */
    public function mkdir($savepath)
    {
        return true;
    }

    /**
     * 保存指定文件
     * @param  array $file 保存的文件信息
     * @param  boolean $replace 同名文件是否覆盖
     * @return boolean          保存状态，true-成功，false-失败
     */
    public function save(&$file, $replace = true)
    {
        $content = fopen($file['tmp_name'], 'r');
        $client = $this->client();

        #putObject
        try {
            $result = $client->putObject(array(
                'Bucket' => C("COS_BUCKET").'-'.C('COS_APPID'),
                'Key' =>$file['savename'],
                'Body' => $content,
                'ServerSideEncryption' => 'AES256'));
            return array('code'=>1,'result'=>$result->getData());
        } catch (\Exception $e) {
            return array('code'=>-1,'result'=>"$e\n");
        }
    }

    /**
     * 上传文件流
     * @param $srcPath 本地文件绝对路径
     * @param $key 文件名
     */
    public function uploadFileStream($srcPath)
    {
        $client = $this->client();
        $key = C('MODEL_PREFIX') . '/' . date('Y') . '/' . date('m') . '/' .$this->config['savename'];
        try {
            $result = $client->putObject(array(
                'Bucket' => C("COS_BUCKET") . '-' . C('COS_APPID'),
                'Key' => $key,
                'Body' => fopen($srcPath, 'rb')));
            return array('code' => 1, 'result' => $result->getData());
        } catch (\Exception $e) {
            return array('code' => -1, 'result' => "$e");
        }
    } /**
 * 上传文件流
 * @param $stream 文件流
 */
    public function uploadFileWithStream($stream)
    {
        $client = $this->client();
        $key = C('MODEL_PREFIX') . '/' . date('Y') . '/' . date('m') . '/' .$this->config['savename'];
        try {
            $result = $client->putObject(array(
                'Bucket' => C("COS_BUCKET") . '-' . C('COS_APPID'),
                'Key' => $key,
                'Body' => $stream));
            return array('code' => 1, 'result' => $result->getData());
        } catch (\Exception $e) {
            return array('code' => -1, 'result' => "$e");
        }
    }
    public function putBucketLifecycle(){
        $cosClient = $this->client();
        try {
            $result = $cosClient->putBucketLifecycle(array(
                'Bucket' => C("COS_BUCKET") . '-' . C('COS_APPID'),
                'Rules' => array(
                    array(
                        'Expiration' => array(
                            'Days' => 1,
                        ),
                        'Filter' => array(
                            'Prefix' => C("MODEL_PREFIX").'/',
                        ),
                        'Status' => 'Enabled',//指明规则是否启用
                        'Transitions' => array(
                        ),
                    ),
                )));
            return array('code' => 1, 'result' => $result->getData());
        } catch (\Exception $e) {
            return array('code' => -1, 'result' => "$e");
        }
    }
    public function getBucketLifecycle(){
        $cosClient = $this->client();
        try {
            $result = $cosClient->getBucketLifecycle(array(
                'Bucket' =>  C("COS_BUCKET") . '-' . C('COS_APPID'),
            ));
            print_r($result);
        } catch (\Exception $e) {
            return array('code' => -1, 'result' => "$e");
        }
    }
    public function deleteBucketLifecycle(){
        $cosClient = $this->client();
        try {
            $result = $cosClient->deleteBucketLifecycle(array(
                'Bucket' => C("COS_BUCKET") . '-' . C('COS_APPID'),
            ));
            print_r($result);
        } catch (\Exception $e) {
            echo($e);
        }
    }

    /**
     * 创建存储桶
     *
     */
    public function createBucket()
    {
        $client = $this->client();
        try {
            $bucket = C("COS_BUCKET"). "-" . C('COS_APPID'); //存储桶名称 格式：BucketName-APPID
            $result = $client->createBucket(array('Bucket' => $bucket));
            //请求成功
            print_r($result);
        } catch (\Exception $e) {
            //请求失败
            echo($e);
        }
    }

    /**
     * 获取最后一次上传错误信息
     * @return string 错误信息
     */
    public function getError()
    {
        return $this->client->errorStr;
    }

    //创建client对象
    function client()
    {
        $client = new \Qcloud\Cos\Client(array('region' => C('COS_REGION'),
            'credentials' => array(
                'appId' => C('COS_APPID'),
                'secretId' => C('COS_KEY'),
                'secretKey' => C('COS_SECRET'))));
        return $client;
    }
}